package com.xwj.coupon.user.mq.consumer;

import com.xwj.coupon.user.common.constant.UserCouponRocketMQConstant;
import com.xwj.coupon.user.framework.idempotent.NoMQDuplicateConsume;
import com.xwj.coupon.user.mq.message.CreateUserCouponMessageBody;
import com.xwj.coupon.user.service.UserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: XuWenjie
 * @Date: 2025-08-20
 * @Description: 用户优惠券创建消息消费者
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = UserCouponRocketMQConstant.USER_COUPON_MQ_TOPIC,
        selectorExpression = UserCouponRocketMQConstant.USER_COUPON_CREATE_TAG,
        consumerGroup = UserCouponRocketMQConstant.USER_COUPON_MQ_CG
)
public class AssignUserCouponMqConsumer implements RocketMQListener<CreateUserCouponMessageBody> {

    @Autowired
    private UserCouponService userCouponService;

    @NoMQDuplicateConsume(
            keyPrefix = "user-coupon-redeem:",
            key = "#message.uniqueKey",
            keyTimeout = 600
    )
    @Override
    public void onMessage(CreateUserCouponMessageBody message) {
        try {
            log.info("收到优惠券创建消息，开始处理: {}", message);

            // 1. 参数校验
            if (message.getUserId() == null || message.getTemplate().getId() == null || message.getReceiveCount() == null) {
                log.error("消息参数不完整: {}", message);
                return;
            }
            // 2. 调用服务创建用户优惠券
            userCouponService.coreAssignUserCoupon(message.getTemplate(), message.getReceiveCount(), message.getUserId());
            log.info("优惠券创建消息处理完成: {}", message);
        } catch (Exception e) {
            log.error("处理优惠券创建消息异常: {}", message, e);
            // 可根据业务需求决定是否抛出异常进行重试
            throw new RuntimeException("处理消息失败", e);
        }
    }
}
